# only use in vim
import re
import vim
from moduleports import moduleports
class autoinstance():
    def __init__(self):
        self.param = 0 # there are parameter in instance or not

    def getinstanceinfo(self):
        self.param = 0
        ins_info = vim.current.line
        if re.search("\#",ins_info):
            self.param = 1
            matched = re.search(r"^\s*(\w+)\#\(\s*\)\s*(\w+)",ins_info)
            if matched:
                module = matched.group(1)
                ins_name = matched.group(2)
                return (module,ins_name)
        else:
            matched = re.search(r"^\s*(\w+)\s+(\w+)\s*\(\s*\)\s*;",ins_info)
            if matched:
                module = matched.group(1)
                ins_name = matched.group(2)
                return (module,ins_name)
        return None

    def portins(self):
        mp = moduleports()
        mp.getfiles()
        if self.getinstanceinfo():
            (module,ins_name) = self.getinstanceinfo()
        else:
            return
        ports = mp.getmoduleports(module)
        if ports:
            portsinfo,portsname=ports
            cl = vim.current.window.cursor[0] -1
            buf = vim.current.buffer
            buf[cl]=module+" "+ins_name+"("
            n = 0
            max_len = 0
            for p in portsname:
                if len(p) > max_len:
                    max_len = len(p)
            for p in portsname:
                if n < len(portsname)-1:
                    ptrn = ".{:"+str(max_len)+"s} ( {:"+str(max_len)+"s} ),"
                    buf.append(ptrn.format(p,p),cl+n+1)
                else:
                    ptrn = ".{:"+str(max_len)+"s} ( {:"+str(max_len)+"s} )"
                    buf.append(ptrn.format(p,p),cl+n+1)

                n+=1

            buf.append(");",cl+n+1)
            vim.command(str(cl)+","+str(cl+n+1)+"normal ==")

            vim.command(str(cl)+","+str(cl+n)+"normal ==")


if __name__=="__main__":
    test = autoinstance()
    test.getinstanceinfo(["d"],0)
